package com.zxisl.util;

import com.google.common.collect.Maps;
import com.zxisl.init.Init;
import org.apache.log4j.Logger;
import org.dom4j.Element;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

import java.io.IOException;
import java.net.InetAddress;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * elasticsearch工具类
 *
 * @author zhouyong
 */
public class ESUtils {

    public static Logger esUtilsLogger = Logger.getLogger(ESUtils.class);
    private static Map<String, Object> esMap = new HashMap<String, Object>();
    // 设置client.transport.sniff为true来使客户端去嗅探整个集群的状态，把集群中其它机器的ip地址加到客户端中，
    static Settings settings = Settings.settingsBuilder().put("cluster.name", esMap.get("clusterName")).put("client.transport.sniff", true).build();

    static {
        getEsConfig();
    }

    /**
     * 创建client
     *
     * @return
     */
    private static TransportClient createClient() {
        TransportClient client = null;
        try {
            Integer esPort = Integer.parseInt(esMap.get("esPort").toString());
            String[] esHosts = (String[]) esMap.get("esHosts");
            //这是第一个优化点 以前加了一个点，现在加上所有点
            if (esHosts.length > 0) {
                client = TransportClient.builder().settings(settings).build()
                        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(esHosts[0]), esPort));
                if (esHosts.length > 1) {
                    for (int i = 1; i < esHosts.length; i++) {
                        client = client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(esHosts[i]), esPort));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }

    /**
     * 取得client
     *
     * @return
     */
    public static TransportClient getTransportClient() {
        return createClient();
    }

    /**
     * <root>
     * <clusterName></clusterName>
     * <esHosts></esHosts>
     * <esPort></esPort>
     * </root>
     *
     * @return
     */
    public static Map<String, Object> getEsConfig() {
        String xPath = "/root";
        String fileName = "esInfo.xml";
        try {
            Element dbElement = Init.getElement(xPath, fileName);
            //这里应该是传入xPath 然后获取数据
            String clusterName = dbElement.elementText("clusterName");
            String esHosts = dbElement.elementText("esHosts");
            String esPort = dbElement.elementText("esPort");
            esMap.put("clusterName", clusterName);
            esMap.put("esHosts", esHosts.split(","));
            esMap.put("esPort", esPort);
            return esMap;
        } catch (Exception e) {
            esUtilsLogger.info(e.getMessage());
            return null;
        }
    }

    /**
     * 执行保存数据
     *
     * @param client
     * @param index
     * @param type
     * @param datas
     * @throws IOException
     * @throws ParseException
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public void execute(TransportClient client, String index, String type, List<HashMap<String, Object>> datas) throws IOException, ParseException, InterruptedException, ExecutionException {
        long startTime = System.currentTimeMillis();
        System.out.println("execute start: " + startTime);
        if (!index_exists(client, index)) {
            create_index_type_mapping(client, index, type);
            bulk_post_document(client, index, type, datas);
        } else {
            bulk_post_document(client, index, type, datas);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("execute end: " + (endTime - startTime));
    }

    /**
     * 判断索引是否存在
     */
    private boolean index_exists(TransportClient client, String index) {
        ActionFuture<IndicesExistsResponse> response = client.admin().indices().exists(Requests.indicesExistsRequest(index));
        return response.actionGet().isExists();
    }

    /**
     * 创建mailInfo的索引
     */
    public void create_index_type_mapping(TransportClient client, String index, String type) throws IOException {
        XContentBuilder builder_mapping = XContentFactory.jsonBuilder().startObject()
                .startObject(type)      //type名
                .startObject("properties")        //属性
                .startObject("subject").field("type", "string").endObject()
                .startObject("from").field("type", "string").endObject()
                .startObject("receiveAddress").field("type", "string").endObject()
                .startObject("copyTo").field("type", "string").endObject()
                .startObject("blindCopy").field("type", "string").endObject()
                .startObject("sentDate").field("type", "string").endObject()
                .startObject("isSeen").field("type", "boolean").endObject()
                .startObject("priority").field("type", "string").endObject()
                .startObject("isReplySign").field("type", "boolean").endObject()
                .startObject("content").field("type", "string").endObject()
                .endObject()
                .endObject().endObject();
        Map<String, String> settings = Maps.newHashMap();
        settings.put("number_of_shards", "5");
        settings.put("number_of_replicas", "1");

        ActionFuture<CreateIndexResponse> response = client.admin().indices().create(Requests.createIndexRequest(index).settings(settings).mapping(type, builder_mapping));
        System.out.println("isAcknowledged: " + response.actionGet().isAcknowledged());
    }

    /**
     * 批量添加索引数据
     *
     * @throws ParseException
     * @throws ExecutionException
     * @throws InterruptedException
     */
    private void bulk_post_document(TransportClient client, String index, String type, List<HashMap<String, Object>> datas) throws ParseException, InterruptedException, ExecutionException {
        BulkRequest request = Requests.bulkRequest();
        for (Map<String, Object> data : datas) {
            request.add(Requests.indexRequest(index).type(type).source(data));
        }
        //执行批量处理
        client.bulk(request);
    }

}